import React, { useState, useImperativeHandle, forwardRef } from "react";
import { Tabs, ConfigProvider } from "antd";

interface PageTabsProps {
  onAddOrRemoveTab?: (action: string, event: any) => void;
}

export interface PageTabsRef {
  handleAddOrRemoveTab: (action: string, event: any) => void;
}

interface TabItem {
  key: string;
  label: string;
  children: React.ReactNode;
}

const PageTabs = forwardRef<PageTabsRef, PageTabsProps>(
  ({ onAddOrRemoveTab }: PageTabsProps, ref: React.Ref<PageTabsRef>) => {
    // 页签数组状态
    const [tabItems, setTabItems] = useState<TabItem[]>([
      // {
      //   key: "1",
      //   label: "Tab 1",
      //   children: "Content of Tab Pane 1",
      // },
      // {
      //   key: "2",
      //   label: "Tab 2",
      //   children: "Content of Tab Pane 2",
      // },
      // {
      //   key: "3",
      //   label: "Tab 3",
      //   children: "Content of Tab Pane 3",
      // },
    ]);

    // 当前激活 tab 面板的 key 状态
    const [activeKey, setActiveKey] = useState("1");

    // 新增和删除页签的回调函数
    const handleAddOrRemoveTab = (action: string, event: any) => {
      const targetKey = event;
      const items = tabItems;
      if (action === "add") {
        // 获取页签数组

        // 判断当newKey不存在时再新增页签
        if (!items.find((item: TabItem) => item.key === event.key)) {
          const newItem = {
            key: event.key,
            label: event.label,
            children: (
              <div
                className="narrow-scrollbar overflow-auto"
                style={{ height: "calc(100vh - 116px)"}}
              >
                {event.children}
              </div>
            ),
          };
          const newItems = [...items, newItem];
          setTabItems(newItems); // 设置页签数组
        }
        setActiveKey(event.key); // 设置当前页签Key
      } else if (action === "remove") {
        const newItems = items.filter((item: TabItem) => item.key !== targetKey);
        setTabItems(newItems);
      }
      onAddOrRemoveTab?.(action, event);
    };

    useImperativeHandle(ref, () => ({
      handleAddOrRemoveTab,
    }));

    return (
      <ConfigProvider theme={{ components: { Tabs: { margin: 0 } } }}>
        <Tabs
          size="small"
          type="editable-card"
          items={tabItems}
          onEdit={(event, action) => handleAddOrRemoveTab(action, event)}
          hideAdd
          onChange={(activeKey) => setActiveKey(activeKey)}
          activeKey={activeKey}
        />
      </ConfigProvider>
    );
  }
);

export default PageTabs;
